home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17441 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  73 lines

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: casting w/ virtual base classes
  5. Date: 15 Apr 1996 23:34:19 GMT
  6. Organization: Borland International
  7. Message-ID: <4kumdr$nki@druid.borland.com>
  8. References: <31728499.6201DD56@unisql.com>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <31728499.6201DD56@unisql.com>, edhill@unisql.com says...
  15. >
  16. >I have the following class hierarchy
  17. >
  18. >class Derived : public virtual Base {...};
  19. >
  20. >Suppose there is a function foo that returns a pointer to a virtual
  21. >base class.
  22. >
  23. >        Base* foo(void) {...}
  24. >
  25. >Now, in my program I have a variable declared as a pointer to Derived.
  26. >
  27. >        int main() {
  28. >                Derived *dp;
  29. >                ...
  30. >                exit 0;
  31. >        }
  32. >
  33. >Book Explanation:
  34. >=================
  35. >In a virtual derivation, the derived class object contains the derived
  36. >part and a pointer to the virtual base part. The virtual base class is
  37. >not contained within the derived class object.
  38. >==================
  39. >
  40. >My compiler does not allow either of the two following statements:
  41. >
  42. >        Derived *dp1 = foo();
  43. >        Derived *dp2 = (Derived *) foo();
  44. >
  45. >error: cast: Base* ->derived dp2*; Base is virtual base
  46. >
  47. >Ok, fine...
  48. >
  49. >However, the following compiles:
  50. >
  51. >        Derived *dp = (Derived *) (void *) foo();
  52. >
  53. >Then, I'm able to access members of Derived and get correct data,
  54. >remember foo() returns a pointer to a virtual base.
  55. >
  56. >        dp->num; // for example
  57. >
  58. >===
  59. >Q1: Is the double cast legal? Why? / Why not?
  60.  
  61. Yes, it is legal. It is not useful, however.
  62.  
  63. >Q2: How is it possible when from the book explanation, virtual base
  64. >    is in a different address space and pointed to from the derived
  65. >    class object.
  66.  
  67. It did not say that the virtual base is in a different address space. I have no 
  68. idea why this code happened to work. It was luck, nothing more. Don't do this. 
  69. The only reliable way to get from a pointer to a virtual base to a pointer to 
  70. derived is with a dynamic_cast.
  71.     -- Pete
  72.  
  73.